/**
 * 统计服务层
 */
const userDao = require('../dao/userDao');
const courseDao = require('../dao/courseDao');
const gameDao = require('../dao/gameDao');
const dailyDao = require('../dao/dailyDao');
const detectionDao = require('../dao/detectionDao');
const { validateEnum } = require('../utils/validation');

/**
 * 获取用户学习统计服务
 * @param {number} userId - 用户ID
 * @param {Object} query - 查询参数
 * @returns {Object} 用户学习统计数据
 */
const getUserLearningStats = async (userId, query) => {
  const { period = 'month' } = query;

  // 验证时间周期
  const periodValidation = validateEnum(period, ['day', 'week', 'month', 'year', 'all'], '时间周期');
  if (!periodValidation.isValid) {
    throw new Error(periodValidation.message);
  }

  // 获取各模块统计数据
  const courseStats = await getCourseStats(userId, period);
  const gameStats = await getGameStats(userId, period);
  const dailyStats = await getDailyPracticeStats(userId, period);
  const detectionStats = await getDetectionStats(userId, period);

  // 计算总体统计
  const totalStats = {
    totalStudyTime: courseStats.totalTime + gameStats.totalTime + dailyStats.totalTime + detectionStats.totalTime,
    totalActivities: courseStats.count + gameStats.count + dailyStats.count + detectionStats.count,
    averageScore: calculateAverageScore([
      courseStats.averageScore,
      gameStats.averageScore,
      dailyStats.averageScore,
      detectionStats.averageScore
    ]),
    streak: await getUserStreak(userId)
  };

  return {
    period,
    total: totalStats,
    courses: courseStats,
    games: gameStats,
    dailyPractice: dailyStats,
    detection: detectionStats,
    trends: await getLearningTrends(userId, period)
  };
};

/**
 * 获取用户成就统计服务
 * @param {number} userId - 用户ID
 * @returns {Object} 用户成就统计数据
 */
const getUserAchievements = async (userId) => {
  const user = await userDao.findById(userId);
  if (!user) {
    throw new Error('用户不存在');
  }

  // 获取各类成就
  const achievements = {
    learning: await getLearningAchievements(userId),
    social: await getSocialAchievements(userId),
    streak: await getStreakAchievements(userId),
    score: await getScoreAchievements(userId)
  };

  // 计算总成就数
  const totalAchievements = Object.values(achievements).reduce((total, category) => {
    return total + category.length;
  }, 0);

  return {
    total: totalAchievements,
    achievements,
    level: calculateUserLevel(user.experience || 0),
    experience: user.experience || 0,
    nextLevelExp: getNextLevelExperience(user.experience || 0)
  };
};

/**
 * 获取排行榜统计服务
 * @param {Object} query - 查询参数
 * @returns {Object} 排行榜统计数据
 */
const getLeaderboardStats = async (query) => {
  const { type = 'experience', period = 'month', limit = 10 } = query;

  // 验证排行榜类型
  const typeValidation = validateEnum(type, ['experience', 'studyTime', 'courseCount', 'gameScore', 'streak'], '排行榜类型');
  if (!typeValidation.isValid) {
    throw new Error(typeValidation.message);
  }

  // 验证时间周期
  const periodValidation = validateEnum(period, ['day', 'week', 'month', 'year', 'all'], '时间周期');
  if (!periodValidation.isValid) {
    throw new Error(periodValidation.message);
  }

  let rankings = [];

  switch (type) {
    case 'experience':
      rankings = await getExperienceRankings(period, limit);
      break;
    case 'studyTime':
      rankings = await getStudyTimeRankings(period, limit);
      break;
    case 'courseCount':
      rankings = await getCourseCountRankings(period, limit);
      break;
    case 'gameScore':
      rankings = await getGameScoreRankings(period, limit);
      break;
    case 'streak':
      rankings = await getStreakRankings(limit);
      break;
  }

  return {
    type,
    period,
    rankings: rankings.map((ranking, index) => ({
      rank: index + 1,
      userId: ranking.user_id,
      username: ranking.user ? ranking.user.username : '',
      nickname: ranking.user ? ranking.user.nickname : '',
      avatar: ranking.user ? ranking.user.avatar : '',
      value: ranking.value,
      change: ranking.change || 0 // 排名变化
    }))
  };
};

/**
 * 获取系统统计概览服务
 * @returns {Object} 系统统计概览数据
 */
const getSystemOverview = async () => {
  const [
    userStats,
    courseStats,
    gameStats,
    dailyStats,
    detectionStats
  ] = await Promise.all([
    getUserOverviewStats(),
    getCourseOverviewStats(),
    getGameOverviewStats(),
    getDailyOverviewStats(),
    getDetectionOverviewStats()
  ]);

  return {
    users: userStats,
    courses: courseStats,
    games: gameStats,
    dailyPractice: dailyStats,
    detection: detectionStats,
    updatedAt: new Date()
  };
};

/**
 * 获取课程统计（辅助函数）
 */
const getCourseStats = async (userId, period) => {
  const stats = await courseDao.getUserCourseStats(userId, period);
  return {
    count: stats.enrolled_courses || 0,
    completed: stats.completed_courses || 0,
    totalTime: stats.total_study_time || 0,
    averageScore: parseFloat(stats.average_progress || 0)
  };
};

/**
 * 获取游戏统计（辅助函数）
 */
const getGameStats = async (userId, period) => {
  const stats = await gameDao.getUserGameStats(userId, period);
  return {
    count: stats.games_played || 0,
    totalTime: stats.total_play_time || 0,
    averageScore: parseFloat(stats.average_score || 0),
    bestScore: stats.best_score || 0
  };
};

/**
 * 获取每日练习统计（辅助函数）
 */
const getDailyPracticeStats = async (userId, period) => {
  const stats = await dailyDao.getUserPracticeStats(userId, period);
  return {
    count: stats.completed_practices || 0,
    totalTime: stats.total_time_spent || 0,
    averageScore: parseFloat(stats.average_score || 0),
    streak: stats.current_streak || 0
  };
};

/**
 * 获取语音检测统计（辅助函数）
 */
const getDetectionStats = async (userId, period) => {
  const stats = await detectionDao.getUserDetectionStats(userId, period);
  return {
    count: stats.total_evaluations || 0,
    totalTime: stats.total_duration || 0,
    averageScore: parseFloat(stats.average_score || 0),
    bestScore: stats.best_score || 0
  };
};

/**
 * 计算平均分（辅助函数）
 */
const calculateAverageScore = (scores) => {
  const validScores = scores.filter(score => score > 0);
  if (validScores.length === 0) return 0;
  return validScores.reduce((sum, score) => sum + score, 0) / validScores.length;
};

/**
 * 获取用户连续天数（辅助函数）
 */
const getUserStreak = async (userId) => {
  const user = await userDao.findById(userId);
  return user ? (user.streak || 0) : 0;
};

/**
 * 获取学习趋势（辅助函数）
 */
const getLearningTrends = async (userId, period) => {
  // 这里可以实现更复杂的趋势分析
  // 例如：学习时间趋势、分数趋势、活跃度趋势等
  return {
    studyTimeGrowth: 0, // 学习时间增长率
    scoreImprovement: 0, // 分数提升率
    activityIncrease: 0 // 活跃度增长率
  };
};

/**
 * 获取学习成就（辅助函数）
 */
const getLearningAchievements = async (userId) => {
  const achievements = [];
  
  // 这里可以实现具体的成就检查逻辑
  // 例如：完成课程数量、学习时间、连续学习等
  
  return achievements;
};

/**
 * 获取社交成就（辅助函数）
 */
const getSocialAchievements = async (userId) => {
  return []; // 社交相关成就
};

/**
 * 获取连续成就（辅助函数）
 */
const getStreakAchievements = async (userId) => {
  return []; // 连续学习成就
};

/**
 * 获取分数成就（辅助函数）
 */
const getScoreAchievements = async (userId) => {
  return []; // 高分成就
};

/**
 * 计算用户等级（辅助函数）
 */
const calculateUserLevel = (experience) => {
  // 简单的等级计算公式
  return Math.floor(experience / 1000) + 1;
};

/**
 * 获取下一等级所需经验（辅助函数）
 */
const getNextLevelExperience = (currentExp) => {
  const currentLevel = calculateUserLevel(currentExp);
  return currentLevel * 1000 - currentExp;
};

/**
 * 获取经验排行榜（辅助函数）
 */
const getExperienceRankings = async (period, limit) => {
  return await userDao.getExperienceRankings(period, limit);
};

/**
 * 获取学习时间排行榜（辅助函数）
 */
const getStudyTimeRankings = async (period, limit) => {
  return await userDao.getStudyTimeRankings(period, limit);
};

/**
 * 获取课程数量排行榜（辅助函数）
 */
const getCourseCountRankings = async (period, limit) => {
  return await courseDao.getCourseCountRankings(period, limit);
};

/**
 * 获取游戏分数排行榜（辅助函数）
 */
const getGameScoreRankings = async (period, limit) => {
  return await gameDao.getGameScoreRankings(period, limit);
};

/**
 * 获取连续天数排行榜（辅助函数）
 */
const getStreakRankings = async (limit) => {
  return await userDao.getStreakRankings(limit);
};

/**
 * 获取用户概览统计（辅助函数）
 */
const getUserOverviewStats = async () => {
  return {
    total: await userDao.getTotalUserCount(),
    active: await userDao.getActiveUserCount(),
    newToday: await userDao.getNewUserCount('today'),
    newThisWeek: await userDao.getNewUserCount('week')
  };
};

/**
 * 获取课程概览统计（辅助函数）
 */
const getCourseOverviewStats = async () => {
  return {
    total: await courseDao.getTotalCourseCount(),
    active: await courseDao.getActiveCourseCount(),
    totalEnrollments: await courseDao.getTotalEnrollmentCount()
  };
};

/**
 * 获取游戏概览统计（辅助函数）
 */
const getGameOverviewStats = async () => {
  return {
    total: await gameDao.getTotalGameCount(),
    totalPlays: await gameDao.getTotalPlayCount(),
    averageScore: await gameDao.getAverageScore()
  };
};

/**
 * 获取每日练习概览统计（辅助函数）
 */
const getDailyOverviewStats = async () => {
  return {
    totalPractices: await dailyDao.getTotalPracticeCount(),
    completionRate: await dailyDao.getCompletionRate()
  };
};

/**
 * 获取语音检测概览统计（辅助函数）
 */
const getDetectionOverviewStats = async () => {
  return {
    totalEvaluations: await detectionDao.getTotalEvaluationCount(),
    averageScore: await detectionDao.getAverageScore()
  };
};

module.exports = {
  getUserLearningStats,
  getUserAchievements,
  getLeaderboardStats,
  getSystemOverview
};
